<template>
	<view class="container">
		<!-- 顶部大图轮播 -->
		<view v-if="imageList.length > 0" class="top-swiper-wrap">
			<swiper class="top-swiper" :indicator-dots="false" :current="current" @change="onSwiperChange">
				<swiper-item v-for="(img, idx) in imageList" :key="idx">
					<image :src="getImageUrl(img.url || img)" class="swiper-image" mode="aspectFill" @tap="previewImage(imageList, idx)" />
				</swiper-item>
			</swiper>
			<view class="img-count">{{current + 1}}/{{imageList.length}}</view>
		</view>
		
		<!-- 文章信息 -->
		<view v-if="article" class="article-header">
			<text class="article-title">{{getArticleField('title')}}</text>
			<view class="article-meta">
				<text class="meta-item">作者：{{getArticleField('author') || '未知'}}</text>
				<text class="meta-item">发布时间：{{formatDate(getArticleField('datetime'))}}</text>
				<text class="meta-item">浏览：{{getArticleField('hit') || 0}}</text>
			</view>
		</view>
		
		<!-- 文章描述 -->
		<view v-if="getArticleField('description')" class="article-desc">
			<text class="desc-text">{{getArticleField('description')}}</text>
		</view>
		
		<!-- 图片列表 -->
		<view v-if="imageList.length > 0" class="image-list">
			<image
				v-for="(img, idx) in imageList"
				:key="idx"
				:src="getImageUrl(img.url || img)"
				class="list-image"
				mode="widthFix"
				@tap="previewImage(imageList, idx)"
				@error="onImageError"
			/>
		</view>
		
		<!-- 文章内容 -->
		<view v-if="getArticleField('details')" class="article-content">
			<text class="content-title">文章详情</text>
			<rich-text :nodes="getArticleField('details') || '暂无内容'" class="content-text"></rich-text>
		</view>
		
		<!-- 文章标签 -->
		<view v-if="getArticleField('tags')" class="article-tags">
			<text class="tags-title">标签</text>
			<view class="tags-list">
				<text 
					v-for="tag in getTagArray(getArticleField('tags'))" 
					:key="tag" 
					class="tag-item"
					@tap="searchByTag(tag)"
				>
					{{tag}}
				</text>
			</view>
		</view>
		
		<!-- 推荐文章 -->
		<view v-if="recommendArticles.length > 0" class="recommend-section">
			<view class="section-title">
				<text class="title-text">推荐文章</text>
			</view>
			<view class="recommend-list">
				<view
					v-for="item in recommendArticles"
					:key="item.id"
					class="recommend-item"
					@tap="goDetail(item)"
				>
					<image
						v-if="getFirstImage(item.contentImg || item.content_img || item.litpic)"
						:src="getFirstImage(item.contentImg || item.content_img || item.litpic)"
						mode="aspectFill"
						class="recommend-image"
						@error="onImageError"
					/>
					<view class="recommend-info">
						<text class="recommend-title">{{item.contentTitle || item.content_title || item.title}}</text>
						<text class="recommend-desc">{{item.contentDescription || item.content_description || item.descrip || '暂无描述'}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部操作区 -->
		<view class="footer-actions">
			<button class="action-btn back-btn" @tap="goBack">返回列表</button>
		</view>
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading">
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 空状态 -->
		<view v-if="!loading && !article" class="empty-state">
			<text class="empty-text">文章不存在</text>
		</view>
		
		<!-- 错误状态 -->
		<view v-if="error" class="error-container">
			<text class="error-text">{{error}}</text>
			<button @tap="retry" class="retry-btn">重试</button>
		</view>
		
		<!-- 快速分享组件 -->
		<quick-share 
			v-if="article && !loading && !error"
			type="article"
			:targetId="article.id"
			:title="getArticleField('title')"
			:description="getArticleField('description') || ''"
			:image="getFirstImage(getArticleField('img'))"
		/>
	</view>
</template>

<script>
import { articleApi } from '@/api/config';
import config from '@/config';
import QuickShare from '@/components/QuickShare.vue';

export default {
	components: {
		QuickShare
	},
	data() {
		return {
			article: null,
			imageList: [],
			recommendArticles: [],
			loading: false,
			error: '',
			current: 0,
			isLoggedIn: false
		}
	},
	onLoad(options) {
		console.log('[详情页] 页面加载, 参数:', options);
		
		this.checkLoginStatus(options);
	},
	// 分享给好友（小程序专用）
	onShareAppMessage() {
		if (!this.article) return {};
		
		return {
			title: this.getArticleField('title'),
			path: `/pages/detail/detail?id=${this.article.id}`,
			imageUrl: this.getFirstImage(this.getArticleField('img'))
		};
	},
	// 分享到朋友圈（小程序专用）
	onShareTimeline() {
		if (!this.article) return {};
		
		return {
			title: this.getArticleField('title'),
			query: `id=${this.article.id}`,
			imageUrl: this.getFirstImage(this.getArticleField('img'))
		};
	},
	methods: {
		// 检查登录状态
		checkLoginStatus(options) {
			try {
				const userInfoStr = uni.getStorageSync('userInfo');
				if (!userInfoStr) {
					console.log('[详情页] 未找到用户信息，需要登录');
					this.redirectToLogin();
					return;
				}
				
				const userInfo = JSON.parse(userInfoStr);
				const loginTime = userInfo.loginTime || 0;
				const currentTime = new Date().getTime();
				
				// 检查登录是否过期（24小时）
				if (currentTime - loginTime > 24 * 60 * 60 * 1000) {
					console.log('[详情页] 登录已过期，需要重新登录');
					this.redirectToLogin();
					return;
				}
				
				this.isLoggedIn = true;
		
		if (options.id) {
					console.log('[详情页] 文章ID:', options.id);
			this.loadArticleDetail(options.id);
		} else {
			console.error('[详情页] 缺少文章ID参数');
			this.error = '缺少文章ID参数';
				}
			} catch (error) {
				console.error('[详情页] 检查登录状态失败:', error);
				this.redirectToLogin();
			}
		},
		
		// 重定向到登录页
		redirectToLogin() {
			uni.redirectTo({
				url: '/pages/login/login',
				fail: (err) => {
					console.error('[详情页] 跳转到登录页失败:', err);
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}
			});
		},
		
		async loadArticleDetail(id) {
			try {
				this.loading = true;
				this.error = '';
				
				console.log('[详情页] 开始加载文章详情, ID:', id);
				
				// 调用文章详情接口
				const detailRes = await articleApi.getDetail(id);
				
				// 检查是否返回了HTML内容
				if (typeof detailRes === 'string' && detailRes.includes('<html>')) {
					console.error('[详情页] 服务器返回了HTML内容，可能需要登录');
					this.redirectToLogin();
					return;
				}
				
				if (detailRes.code === 200) {
					this.article = detailRes.data;
					console.log('[详情页] 文章详情加载成功:', this.article);
					
					// 解析图片数据
					this.parseImages();
					
					// 获取推荐文章
					this.loadRecommendArticles();
					
					// 更新标题
					uni.setNavigationBarTitle({
						title: this.getArticleField('title') || '文章详情'
					});
				} else {
					console.error('[详情页] API返回错误:', detailRes);
					throw new Error(detailRes?.msg || '文章不存在');
				}
				
			} catch (error) {
				console.error('[详情页] 加载失败:', error);
				this.error = error.message || '文章加载失败';
				
				// 检查是否是登录相关错误
				if (error.message && (
					error.message.includes('登录') || 
					error.message.includes('session') || 
					error.message.includes('授权')
				)) {
					this.redirectToLogin();
				}
			} finally {
				this.loading = false;
			}
		},
		
		// 统一获取文章字段，兼容不同的字段命名
		getArticleField(field) {
			if (!this.article) return '';
			
			const fieldMappings = {
				'title': ['contentTitle', 'content_title', 'title'],
				'author': ['contentAuthor', 'content_author', 'author'],
				'datetime': ['contentDatetime', 'content_datetime', 'date'],
				'hit': ['contentHit', 'content_hit', 'hit'],
				'description': ['contentDescription', 'content_description', 'descrip'],
				'details': ['contentDetails', 'content_details', 'contentText'],
				'tags': ['contentTags', 'content_tags', 'tags'],
				'img': ['contentImg', 'content_img', 'litpic']
			};
			
			const possibleFields = fieldMappings[field] || [];
			for (const f of possibleFields) {
				if (this.article[f] !== undefined && this.article[f] !== null) {
					return this.article[f];
				}
			}
			
			return '';
		},
		
		parseImages() {
			// 解析图片数据
			const imageData = this.getArticleField('img');
			console.log('[详情页] 开始解析图片数据:', imageData);
			
			if (imageData) {
				try {
					if (typeof imageData === 'string') {
						// 尝试解析JSON格式
						if (imageData.startsWith('[')) {
							this.imageList = JSON.parse(imageData);
						} else {
							// 分隔符格式
							this.imageList = imageData.split(',').map(url => ({url: url.trim()}));
						}
					} else if (Array.isArray(imageData)) {
						this.imageList = imageData;
					} else {
						this.imageList = [];
					}
					console.log('[详情页] 图片列表:', this.imageList);
				} catch (error) {
					console.error('[详情页] 解析图片数据失败:', error);
					this.imageList = [];
				}
			} else {
				this.imageList = [];
			}
		},
		
		async loadRecommendArticles() {
			try {
				const categoryId = this.article?.categoryId || 
								   this.article?.category_id || 
								   this.article?.contentType;
				
				if (!categoryId) {
					console.log('[详情页] 无法获取分类ID，跳过加载推荐文章');
					return;
				}
				
				const params = {
					categoryId: categoryId,
					size: 5
				};
				
				console.log('[详情页] 加载推荐文章, 参数:', params);
				const res = await articleApi.getList(params);
				
				// 检查是否返回了HTML内容
				if (typeof res === 'string' && res.includes('<html>')) {
					console.error('[详情页] 服务器返回了HTML内容，可能需要登录');
					return; // 推荐文章不是必须的，失败可以忽略
				}
				
				if (res.code === 200) {
					// 过滤掉当前文章
					const allArticles = res.data.rows || [];
					this.recommendArticles = allArticles.filter(item => item.id !== this.article.id).slice(0, 5);
					console.log('[详情页] 推荐文章数量:', this.recommendArticles.length);
				}
			} catch (error) {
				console.error('[详情页] 推荐文章加载失败:', error);
			}
		},
		
		retry() {
			this.error = '';
			if (this.article?.id) {
				this.loadArticleDetail(this.article.id);
			}
		},
		
		goDetail(item) {
			console.log('[详情页] 跳转详情:', item);
			uni.navigateTo({
				url: `/pages/detail/detail?id=${item.id}`
			});
		},
		
		getFirstImage(images) {
			if (!images) return '';
			try {
				// 空数组字符串直接返回空
				if (typeof images === 'string' && images.trim() === '[]') return '';
				let imageList = images;
				if (typeof images === 'string') {
					const cleanStr = images.replace(/\\/g, '');
					imageList = JSON.parse(cleanStr);
				}
				if (Array.isArray(imageList) && imageList.length > 0) {
					const firstImage = imageList[0];
					let imageUrl = '';
					if (typeof firstImage === 'object' && firstImage.url) {
						imageUrl = firstImage.url;
					} else if (typeof firstImage === 'string') {
						imageUrl = firstImage;
					}
					if (imageUrl) {
						return this.getImageUrl(imageUrl);
					}
				}
				return '';
			} catch (error) {
				console.error('[详情页] 获取第一张图片失败:', error);
				return '';
			}
		},
		
		getImageUrl(url) {
			if (!url) return '';
			if (url.startsWith('http://') || url.startsWith('https://')) {
				return url;
			}
			return `${config.baseUrl}${url}`;
		},
		
		previewImage(images, currentIndex) {
			const urls = images.map(img => this.getImageUrl(img.url || img));
			uni.previewImage({
				urls: urls,
				current: urls[currentIndex],
				loop: true,
				indicator: 'number'
			});
		},
		
		onSwiperChange(e) {
			this.current = e.detail.current;
		},
		
		formatDate(dateStr) {
			if (!dateStr) return '';
			try {
				// 兼容 iOS：将 "2025-06-29 23:40:03" 替换为 "2025/06/29 23:40:03"
				let fixedStr = dateStr.replace(/-/g, '/');
				// 只替换日期部分，防止 "2025-06-29T23:40:03" 变成 "2025/06/29T23:40:03"
				if (dateStr.indexOf('T') > -1) {
					fixedStr = dateStr;
				}
				const date = new Date(fixedStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			} catch (error) {
				console.error('[详情页] 日期格式化失败:', error);
				return dateStr;
			}
		},
		
		onImageError(e) {
			console.error('[详情页] 图片加载失败:', e);
		},

		// 返回列表页
		goBack() {
			uni.navigateBack({
				delta: 1,
				fail: function() {
					// 如果返回失败，可能是直接进入的详情页，跳转到首页
					uni.switchTab({
						url: '/pages/index/index',
						fail: function() {
							// 如果switchTab也失败了，使用redirectTo
							uni.redirectTo({
								url: '/pages/index/index'
							});
						}
					});
				}
			});
		},
		
		// 获取标签数组
		getTagArray(tags) {
			if (!tags) return [];
			if (typeof tags === 'string') {
				return tags.split(',').filter(tag => tag.trim() !== '');
			}
			return [];
		},
		
		// 通过标签搜索
		searchByTag(tag) {
			console.log('[详情页] 搜索标签:', tag);
			uni.navigateTo({
				url: `/pages/index/index?keyword=${encodeURIComponent(tag)}`,
				fail: () => {
					// 如果无法导航，尝试使用switchTab
					uni.switchTab({
						url: '/pages/index/index',
						success: () => {
							// 成功后设置搜索关键词
							getApp().globalData = getApp().globalData || {};
							getApp().globalData.searchKeyword = tag;
						}
					});
				}
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	padding: 15px;
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 80px; /* 为底部操作区留出空间 */
}

.top-swiper-wrap {
	position: relative;
	margin-bottom: 16px;
	border-radius: 12px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.top-swiper {
	width: 100%;
	height: 400rpx;
}
.swiper-image {
	width: 100%;
	height: 400rpx;
}
.img-count {
	position: absolute;
	right: 24rpx;
	bottom: 16rpx;
	color: #fff;
	background: rgba(0,0,0,0.4);
	border-radius: 20rpx;
	padding: 4rpx 12rpx;
	font-size: 24rpx;
}

.article-header {
	background: #fff;
	padding: 15px;
	border-radius: 8px;
	margin-bottom: 15px;
	box-shadow: 0 2px 6px rgba(0,0,0,0.05);
	
	.article-title {
		font-size: 20px;
		font-weight: bold;
		color: #333;
		line-height: 1.4;
		margin-bottom: 15px;
	}
	
	.article-meta {
		display: flex;
		flex-wrap: wrap;
		gap: 12px;
		
		.meta-item {
			font-size: 12px;
			color: #999;
		}
	}
}

.article-desc {
	background: #fff;
	padding: 15px;
	border-radius: 8px;
	margin-bottom: 15px;
	box-shadow: 0 2px 6px rgba(0,0,0,0.05);
	
	.desc-text {
		font-size: 15px;
		color: #666;
		line-height: 1.6;
	}
}

.image-list {
	margin-bottom: 15px;
	.list-image {
		width: 100%;
		margin-bottom: 15px;
		border-radius: 8px;
		box-shadow: 0 2px 6px rgba(0,0,0,0.05);
	}
}

.article-content {
	background: #fff;
	padding: 15px;
	border-radius: 8px;
	margin-bottom: 15px;
	box-shadow: 0 2px 6px rgba(0,0,0,0.05);
	
	.content-title {
		font-size: 17px;
		font-weight: bold;
		color: #333;
		margin-bottom: 15px;
	}
	
	.content-text {
		font-size: 15px;
		color: #333;
		line-height: 1.8;
	}
}

.article-tags {
	background: #fff;
	padding: 15px;
	border-radius: 8px;
	margin-bottom: 15px;
	box-shadow: 0 2px 6px rgba(0,0,0,0.05);
	
	.tags-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 12px;
	}
	
	.tags-list {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		
		.tag-item {
			background: #f2f2f2;
			color: #666;
			font-size: 13px;
			padding: 6px 12px;
			border-radius: 16px;
			box-shadow: 0 1px 3px rgba(0,0,0,0.05);
		}
	}
}

.recommend-section {
	background: #fff;
	padding: 15px;
	border-radius: 8px;
	margin-bottom: 15px;
	box-shadow: 0 2px 6px rgba(0,0,0,0.05);
	
	.section-title {
		margin-bottom: 15px;
		
		.title-text {
			font-size: 17px;
			font-weight: bold;
			color: #333;
		}
	}
	
	.recommend-list {
		.recommend-item {
			display: flex;
			padding: 12px 0;
			border-bottom: 1px solid #f0f0f0;
			
			&:last-child {
				border-bottom: none;
			}
			
			.recommend-image {
				width: 100px;
				height: 70px;
				border-radius: 6px;
				margin-right: 12px;
			}
			
			.recommend-info {
				flex: 1;
				
				.recommend-title {
					font-size: 15px;
					color: #333;
					line-height: 1.4;
					margin-bottom: 8px;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}
				
				.recommend-desc {
					font-size: 13px;
					color: #999;
					line-height: 1.4;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}
			}
		}
	}
}

.footer-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	justify-content: space-around;
	padding: 10px 15px;
	background: #fff;
	box-shadow: 0 -2px 6px rgba(0,0,0,0.05);
	z-index: 100;
	
	.action-btn {
		flex: 1;
		height: 40px;
		line-height: 40px;
		font-size: 14px;
		border-radius: 20px;
		margin: 0 10px;
		
		&.back-btn {
			background-color: #f5f5f5;
			color: #333;
		}
	}
}

.loading, .empty-state {
	padding: 20px 0;
	text-align: center;
}

.loading-text, .empty-text {
	font-size: 14px;
	color: #999;
}

.error-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100vh;
	padding: 20px;
}

.error-text {
	font-size: 16px;
	color: #666;
	margin-bottom: 20px;
	text-align: center;
}

.retry-btn {
	padding: 12px 24px;
	background-color: #007aff;
	color: #fff;
	border-radius: 6px;
	font-size: 16px;
}
</style>